package com.xd.study.activity;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import com.xd.study.R;
import com.xd.study.fragment.LifecycleFragment1;
import com.xd.study.fragment.LifecycleFragment2;

/**
 * Created by DGF on 2015/4/24.
 * 测试步骤：
 * 启动Fragment -- 屏幕锁屏 -- 屏幕解锁 -- 切换到其他Fragment -- 回到桌面 -- 回到应用 -- 退出Fragment
 */
public class FragmentLifecycleActivity extends Activity {

    private boolean isFragment1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_lifecycle);

        LinearLayout linearLayout = (LinearLayout)this.findViewById(R.id.fragment_lifecycle_layout);

        //动态添加Fragment1
        LifecycleFragment1 fragment = new LifecycleFragment1();
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.fragment_lifecycle_layout, fragment);
        //fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();

        isFragment1 = true;

        Button button = (Button)this.findViewById(R.id.fragment_lifecycle_change);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

                if (isFragment1){
                    LifecycleFragment2 fragment2 = new LifecycleFragment2();
                    fragmentTransaction.replace(R.id.fragment_lifecycle_layout, fragment2);
                    isFragment1 =false;
                }else{
                    LifecycleFragment1 fragment1 = new LifecycleFragment1();
                    fragmentTransaction.replace(R.id.fragment_lifecycle_layout, fragment1);
                    isFragment1 =true;
                }

                //fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
            }
        });
    }
}
